package com.sopt.friends.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class MsgListManager {
	JSONArray currentInstance;
	public MsgListManager() {
		// TODO Auto-generated constructor stub
	}
	
	public JSONArray getMsgList(String currentUrl) {
        String url = currentUrl;
        //Log.v("changdoc", "Current Req:"+url);
        try {
            URI uri = new URI("http", url, null);
            HttpGet get = new HttpGet(uri);
            
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            String str = convertStreamToString(entity.getContent());
            JSONObject json = new JSONObject(str);
            //Log.v("changdoc",str);
            currentInstance = json.getJSONArray("result");
			return currentInstance;
        } catch (Exception e) {
        	JSONObject json = new JSONObject();
        	try {
				json.put("result", new JSONObject("{\"exist\":\"Cannot connect ServerT_T\"}"));
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			try {
				currentInstance = json.getJSONArray("result");
			} catch (JSONException e1) {
				return currentInstance;
			}
			return currentInstance;
        } 
    }
    

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8*1024);
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
        return sb.toString();
    }
}
